<?php
namespace Com\Pay;
class HezhongPay{

    private $config = array();

  
    public function __construct($send_data){
        $this->config = $send_data;
    }


    /*生成支付连接*/
    public function getUrl($order_info,$other = array()){

        /* 获取提交的订单交易金额 */
        $price = $order_info['paymoney'];
        //支付成功后跳转地址
        if(!empty($other['returl'])){
            $returnUrl = $other['returl'];
        }else{
            $returnUrl    = $order_info['return_url'];
        }
        if(!empty($other['callback'])){
            $notifyUrl = $other['callback'];
        }else{
            /* 获取提交的后台回调地址 */
            $notifyUrl = 'http://' . $_SERVER['HTTP_HOST'] . '/Api/NotifyCallback/HezhongPayNotify';
        }

        $order_sn = $order_info['ordernumber'];
        $post_data = array(
            'subject' =>   'CbPay',
            'orderSn'    =>    $order_sn,
            'totalAmount' => $price,
            'notify'    => $notifyUrl,
            "spbillCreateIp"  =>  $this->getClientIP(),
            'merurl' => $returnUrl,
            'paystyle' => 8,
            "timestamp"  =>  time(),
            'mchId' => $this->config['mch_id'],
            'channel' => "00",
        );
        if($order_info['banktype'] == 'qq_pay') unset($post_data['paystyle']);
        $post_data['sign'] = $this->getSign($post_data); // Sign签名
        $tar_url = "http://api.youngport.com.cn/api" . $order_info['weburl'];
        $data = http_build_query($post_data);
        $res_arr = json_decode($this->http_post($tar_url, $data) , true);
        $key = ($order_info['banktype'] == 'qq_pay') ? 'qrCode' : 'url';
        if($res_arr['success'] == 'true'){
           $qrcode = $res_arr['data'][$key];
        }else{
            // 各种原因发起支付失败
            $qrcode = '';
        }
        return $qrcode;
    }

    //回调方法，把返回数据处理成统一规定返回
    public function response(){
        $data = json_decode(file_get_contents('php://input') , true);
        $sign = $data['sign'];
        unset($data['sign']);
        $MySign = $this->getSign($data);
        if($sign === $MySign){
                return true;
            }else{
                // 失败
                return false;
            }
        }

   private function getClientIP()
    {
        global $ip;
        if (getenv("HTTP_CLIENT_IP"))
            $ip = getenv("HTTP_CLIENT_IP");
        else if(getenv("HTTP_X_FORWARDED_FOR"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if(getenv("REMOTE_ADDR"))
            $ip = getenv("REMOTE_ADDR");
        else $ip = "Unknow";
        return $ip;
    }

    private function getSign($arr){
        //过滤null和空
        $Parameters = array_filter($arr, function ($v) {
            if ($v === null || $v === '') {
                return false;
            }
            return true;
        });
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String =$this->formatBizQueryParaMap($Parameters, false);
        //签名步骤二：在string后加入KEY
        $String = $String . "&key=" . $this->config['mch_key'];
        //签名步骤三：MD5加密
        $String = md5($String);
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        return $result_;
    }


    /**
     * 作用：格式化参数，签名过程需要使用
     * @param $paraMap
     * @param $urlencode
     * @return string
     */
    private function formatBizQueryParaMap($paraMap, $urlencode){
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = json_encode($v);
            }
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }

        return $reqPar;
    }

    private function http_post($url,$post_data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

//    private function http_post($url, $post_data) {
//        $postdata = http_build_query($post_data);
//        $options = array(
//            'http' => array(
//                'method' => 'POST',
//                'header' => 'Content-Type:application/x-www-form-urlencoded',
//                'content' => $postdata
//            )
//        );
//        $context = stream_context_create($options);
//        $result = file_get_contents($url, false, $context);
//        return $result;
//    }


}
